package com.library.staff.controller;

import com.framework.*;
import com.library.book.service.BookServiceImpl;
import com.library.book.util.BookState;
import com.library.bookClass.service.BookClassServiceImpl;
import com.library.borrow.service.BorrowServiceImpl;
import com.library.borrow.util.BorrowState;
import com.library.circles.service.CirclesServiceImpl;
import com.library.collection.service.CollectionServiceImpl;
import com.library.count.service.CountServiceImpl;
import com.library.entity.*;
import com.library.entity.Collection;
import com.library.evaluate.service.EvaluateServiceImpl;
import com.library.evaluate.util.EvaluateListReturner;
import com.library.payment.service.PaymentServiceImpl;
import com.library.praise.service.PraiseServiceImpl;
import com.library.recommendation.service.RecommendationServiceImpl;
import com.library.relation.service.BookRelationServiceImpl;
import com.library.relation.service.StaffRelationServiceImpl;
import com.library.search.service.SearchServiceImpl;
import com.library.search.util.StaffSearchListReturner;
import com.library.staff.service.StaffServiceImpl;
import com.library.statistic.service.StatisticServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("staff")
public class StaffController {
	
	@Resource
	private StaffServiceImpl staffServiceImpl;
	@Resource
	private BookServiceImpl bookServiceImpl;
	@Resource
	private BookClassServiceImpl bookClassServiceImpl;
	@Resource
	private BorrowServiceImpl borrowServiceImpl;
    @Resource
    private EvaluateServiceImpl evaluateServiceImpl;
	@Resource
	private PraiseServiceImpl praiseServiceImpl;
	@Resource
	private SearchServiceImpl searchServiceImpl;
	@Resource
	private StatisticServiceImpl statisticServiceImpl;
	@Resource
	private CountServiceImpl countServiceImpl;
	@Resource
	private PaymentServiceImpl paymentServiceImpl;
	@Resource
	private CollectionServiceImpl collectionServiceImpl;
	@Resource
	private StaffRelationServiceImpl staffRelationService;
    @Resource
    private CirclesServiceImpl circlesServiceImpl;
	@Resource
	private RecommendationServiceImpl recommendationServiceImpl;
	@Resource
	private BookRelationServiceImpl bookRelationServiceImpl;

	/****************员工**************/
	/* 登录 */
	@RequestMapping("login")
	public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
						@RequestParam("checkCode") String checkCode,
						HttpSession session, HttpServletRequest request) throws ParseException {
		String trueCode = (String) session.getAttribute("verCode");
		if(!checkCode.equalsIgnoreCase(trueCode)){
			request.setAttribute("error","验证码错误,请重新输入");
			return "login";
		}
		Staff sf =this.staffServiceImpl.login(username,password);
		Set<Power> powers = new TreeSet<>(new Comparator<Power>() {
			@Override
			public int compare(Power o1, Power o2) {
				if(o1.getType() > o2.getType()){
					return 1;
				}else if(o1.getType() < o2.getType()){
					return -1;
				}
				return 0;
			}
		});
        if(sf!=null){
			if(sf.isState()){	//是否被禁用
				request.setAttribute("error","该账户已经被禁用，请联系管理员");
				return "login";
			}
			if(sf.getRole() != null)
				powers.addAll(sf.getRole().getPowers());

            //快到期的借单
            List<Borrow> borrows = this.borrowServiceImpl.getCurrentBorrowsByStaff(sf);
            Iterator<Borrow> it = borrows.iterator();
            Borrow borrow;
            for(int i = borrows.size() - 1;i >= 0;--i){
                borrow = borrows.get(i);
                if(borrow.getState() == BorrowState.RETURNED_BOOK.getState() || borrow.getState() == BorrowState.OUTDATE_BOOK.getState()
						|| Integer.parseInt(String.valueOf(borrow.getEndDays()))> 5){
                    borrows.remove(borrow);
                }
            }

            //清除之前的会话信息
			Enumeration em  = session.getAttributeNames();
			while(em.hasMoreElements()){
				session.removeAttribute(em.nextElement().toString());
			}
			session.setAttribute("powers",powers);
			session.setAttribute("role",sf.getRole());
			session.setAttribute("staff",sf);
            session.setAttribute("borrows",borrows);

			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sf.setLastLoginTime(formatter.format(new Date()));
            this.staffServiceImpl.updateStaffLoginTime(sf);

			return "redirect:/staff/bookSearchPage";
		} else{
            request.setAttribute("error","账号密码不一致");
			return "login";
		}

	}

	/*退出登录*/
    @RequestMapping("loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute("user");
        session.removeAttribute("role");
        session.invalidate();

        return "login";
    }

    /* 跳转到修改密码*/
    @RequestMapping("updatePasswordPage")
    public String updatePasswordPage(RedirectAttributes attr,HttpServletRequest request){
        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "staff/staff_password";
    }

    /* 修改密码操作*/
    @RequestMapping(value = "updatePassword",method = RequestMethod.POST)
    public String updatePassword(@RequestParam("old_password") String oldPassword,
                                 @RequestParam("new_password") String newPassword,
                                 HttpSession session,HttpServletRequest request,RedirectAttributes attr){
        Staff staff = (Staff) session.getAttribute("staff");

        if(!Encrypt.SHA512(oldPassword).equals(staff.getPassword())){
            attr.addFlashAttribute("error","原密码不正确");
            return "redirect:/staff/updatePasswordPage";
        }
        staff.setPassword(newPassword);
        this.staffServiceImpl.updateStaffpassword(staff);

        attr.addFlashAttribute("success","修改成功");
		session.setAttribute("staff",staff);
        return "redirect:/staff/updatePasswordPage";
    }

	/* 找回密码 生成验证码操作*/
	@ResponseBody
	@RequestMapping(value = "findPasswordEmailCode",method = RequestMethod.POST)
	public ReturnJson findPasswordEmailCode(@RequestBody Map<String, String> params,HttpSession session){
		String username = params.get("username");
		String subject = "内部图书管理系统_信息找回";
		Map<String,Object> data = new HashMap();

        /*判断员工是否存在*/
		if(this.staffServiceImpl.getStaff(username) == null){
			return new ReturnJson(false,"失败了，用户不存在");
		}else{
			Staff staff = this.staffServiceImpl.getStaff(username);
			String emailCode= String.valueOf((int)(Math.random()*1000000));

			session.setAttribute("emailCode",emailCode);        //邮件随机码
			session.setAttribute("userCode",username);      //用户名码
			new SendMessage().send("companylibrary@sina.com","administrator",staff.getEmail(),subject,emailCode);      /* 发送邮件 */
			return new ReturnJson(true,null,data);
		}
	}

	/* 找回密码*/
	@RequestMapping("findPassword")
	public String findPassword(@RequestParam("username") String username,
							   @RequestParam("emailCode") String emailCode,
							   HttpServletRequest request,HttpSession session){
		String trueCode = (String) session.getAttribute("emailCode");
		Staff staff = this.staffServiceImpl.getStaff(username);

		if(!emailCode.equals(trueCode)) {
			request.setAttribute("error", "验证码错误,请重新输入");
			return "findPassword";
		} else if(staff == null || !username.equals(session.getAttribute("userCode"))){
			request.setAttribute("error", "用户名不存在或者不一致,请重新输入");
			return "findPassword";
		} else {
            /* 发送邮件 */
			String newPassword = trueCode;

			staff.setPassword(newPassword);
			this.staffServiceImpl.updateStaffpassword(staff);
			request.setAttribute("success","密码已设置为验证码,请及时登录并修改密码");
		}
		return "login";
	}

    /*设置自己的信息*/
	@RequestMapping("staffInfoUpdatePage")
	public String staffInfoUpdatePage(HttpSession session,HttpServletRequest request,RedirectAttributes attr){
		Staff staff = (Staff) session.getAttribute("staff");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		Date date = new Date();
		Map paramsMap = new HashMap();

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date); // 设置为当前时间
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月

		paramsMap.put("staff",staff);    //查询指定员工统计数据
		Count count = this.countServiceImpl.getSumCountByParams(paramsMap);
		List<Statistic> statistics = this.statisticServiceImpl.getStatisticsByParams(paramsMap);
		List<Count> counts = this.countServiceImpl.getCountsByParams(paramsMap);

		for(int i = counts.size() - 1;i > 5;--i){
			counts.remove(i);
		}
		for(int i = statistics.size() - 1;i > 5;--i){
			statistics.remove(i);
		}

		int paymentCount = this.paymentServiceImpl.getPaymentCountByParams(paramsMap) == null ? 0 :this.paymentServiceImpl.getPaymentCountByParams(paramsMap).intValue();

        if(attr.getFlashAttributes().get("error") != null)
			request.setAttribute("error",attr.getFlashAttributes().get("error"));
		else if(attr.getFlashAttributes().get("success") != null)
			request.setAttribute("success",attr.getFlashAttributes().get("success"));

        request.setAttribute("count",count);
		request.setAttribute("counts",counts);
		request.setAttribute("paymentCounts",paymentCount);
        request.setAttribute("statistics",statistics);
		request.setAttribute("staff",staff);
		session.setAttribute("staff",staff);
		return "staff/staff_staff_info";
	}

	/* 更新员工信息操作*/
	@RequestMapping(value = "updateStaff",method = RequestMethod.POST)
	public String updateStaff(@RequestParam("staffName") String staffName,
							  @RequestParam("department") String department,
							  @RequestParam("qq") String qq,
							  @RequestParam("email") String email,
                              @RequestParam("staffSign") String staffSign,
						      HttpServletRequest request
			,RedirectAttributes attr){
		Staff staff = (Staff) request.getSession().getAttribute("staff");
		staff.setName(staffName);
		staff.setDepartment(department);
		staff.setQq(qq);
		staff.setEmail(email);
		staff.setStaffSign(staffSign);

		this.staffServiceImpl.updateStaff(staff);
		attr.addFlashAttribute("success","更新成功!");

		return "redirect:/staff/staffInfoUpdatePage";
	}

	/******************借阅书籍****************/
	/*跳转到图书检索 包括图书热门排名*/
	@RequestMapping("bookSearchPage")
	public String bookSearchPage(HttpServletRequest request,RedirectAttributes attr){
		List<BookClass> bc = this.bookClassServiceImpl.getAllBookClasses();
		List<Book> books = this.bookServiceImpl.getAllClassHotBook(5);
		List<StaffSearch> searchs = this.searchServiceImpl.getHotSearch(10);

		if(attr.getFlashAttributes().get("error") != null)
			request.setAttribute("error",attr.getFlashAttributes().get("error"));
		else if(attr.getFlashAttributes().get("success") != null)
			request.setAttribute("success",attr.getFlashAttributes().get("success"));

		request.setAttribute("bookClasses",bc);
		request.setAttribute("books",books);
		request.setAttribute("searchs",searchs);

		return "staff/staff_book_search";
	}

	/*
	* 模糊查找搜索记录
	* return Json
	* */
	@ResponseBody
	@RequestMapping(value = "getSearchsByKey", method = RequestMethod.POST)
	public ReturnJson getSearchsByKey(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		String key = params.get("searchKey");
		List<StaffSearch> staffSearches = this.searchServiceImpl.getSearchByKeyVague(key);
		StaffSearchListReturner staffSearchListReturner = new StaffSearchListReturner(staffSearches);
		Map<String,Object> data = new HashMap();

		data.put("searchs",staffSearchListReturner.getStaffSearchs());
		return new ReturnJson(true,"",data);
	}

	/* 检索图书操作*/
	@RequestMapping(value = "bookSearch",method = RequestMethod.POST)
	public String bookSearch(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
						   @RequestParam(name="pageSize", defaultValue="10") String pageSize,
			               @RequestParam("bookName") String bookName,
						   @RequestParam("author") String author,
						   @RequestParam("publish") String publish,
						   @RequestParam("bookClass") String bookClass,
						   @RequestParam("type") String type,
						   HttpServletRequest request){
		Staff staff = (Staff) request.getSession().getAttribute("staff");
		BookClass bc = this.bookClassServiceImpl.getBookClass(Integer.parseInt(bookClass));
		Page<Book> bookPage;
		String key;		//搜索关键词
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        Map paramsMap = new HashMap();
        Statistic statistic;

        //增加搜索记录
		StaffSearch search;
		if(!bookName.equals("")){
			key = bookName;
		}else if(!author.equals("")) {
			key = author;
		}else{
			key = publish;
		}

		//搜索
		if(this.searchServiceImpl.getSearchByKey(key) != null){
			search =this.searchServiceImpl.getSearchByKey(key);
			search.setSearchCount(search.getSearchCount() + 1);
            search.setStaff(staff);
			this.searchServiceImpl.updateSearch(search);
		} else{
			search = new StaffSearch();
			search.setSearchKey(key);
			search.setSearchCount(1);
            search.setStaff(staff);
			search.setBookClass(bc);
			searchServiceImpl.addSearch(search);
		}

		if(Integer.parseInt(type) == 0){	//精确查找
			if(pageSize.equals("all")){
				List<Book> books = this.bookServiceImpl.getBooks(bookName,author,publish,bc);
				bookPage = new Page<>();
				bookPage.setPageSize(books.size());
				bookPage.setTotalCount(books.size());
				bookPage.setList(books);
				bookPage.setCurrentPageNum(1);
				bookPage.setTotalPageNum(1);
			}else{
				bookPage = this.bookServiceImpl.getBooks(pageNum,Integer.parseInt(pageSize),bookName,author,bc);
			}
		}else{	//模糊查找
			if(pageSize.equals("all")){
				List<Book> books = this.bookServiceImpl.getBooksVague(bookName,author,publish,bc);
				bookPage = new Page<>();
				bookPage.setPageSize(books.size());
				bookPage.setTotalCount(books.size());
				bookPage.setList(books);
				bookPage.setCurrentPageNum(1);
				bookPage.setTotalPageNum(1);
			}else{
				bookPage = this.bookServiceImpl.getBooksVague(pageNum,Integer.parseInt(pageSize),bookName,author,publish,bc);
			}
		}

        paramsMap.put("staff",staff);
        paramsMap.put("bookClass",bc);
        statistic = this.statisticServiceImpl.getStatisticByParams(paramsMap);

        paramsMap.clear();
        paramsMap.put("staff",staff);
        int sumBorrowTime = this.borrowServiceImpl.getBorrowsCountByParams(paramsMap).intValue();
        int sumSearchTime = this.searchServiceImpl.getStaffSearchsCountByParams(paramsMap).intValue();
        Double percentage = 0.0;

		sumBorrowTime = (sumBorrowTime == 0) ? 1: sumBorrowTime;
		sumSearchTime = (sumSearchTime == 0) ? 1: sumSearchTime;

        if(statistic != null){
            statistic.setSearchTime(statistic.getSearchTime() + 1);	//增加借阅次数
            percentage = ((statistic.getBorrowTime() * 100 / sumBorrowTime) * 0.8 + (statistic.getSearchTime() * 100 / sumSearchTime) * 0.2);
            statistic.setPercentage(String.valueOf(percentage.intValue()));
			this.statisticServiceImpl.updateStatistic(statistic);
        } else{		//statistic 为空
            statistic = new Statistic();
            statistic.setBookClass(bc);
            statistic.setBorrowTime(0);
            statistic.setSearchTime(1);
            percentage = ((statistic.getBorrowTime() * 100 / sumBorrowTime) * 0.8 + (statistic.getSearchTime() * 100 / sumSearchTime) * 0.2);
            statistic.setPercentage(String.valueOf(percentage.intValue()));
            statistic.setStaff(staff);
			statistic.setDate(formatter.format(date));
            this.statisticServiceImpl.addStatistic(statistic);
        }

        paramsMap.put("date",formatter.format(date));
        Count count = this.countServiceImpl.getCountByParams(paramsMap);
        if(count != null){
            count.setSearchCount(count.getSearchCount() + 1);
            this.countServiceImpl.updateCount(count);
        }else{
            count = new Count();
            count.setBorrowCount(0);
            count.setStaffCount(0);
            count.setEvaluateCount(0);
            count.setBookCount(0);
            count.setSearchCount(1);
            count.setPaymentCount(this.paymentServiceImpl.getPaymentCostByParams(paramsMap).intValue());
            count.setStaff(staff);
            count.setDate(formatter.format(date));

            this.countServiceImpl.addCount(count);
        }

        request.setAttribute("bookName",bookName);
		request.setAttribute("author",author);
		request.setAttribute("publish",publish);
		request.setAttribute("type",type);
		request.setAttribute("books",bookPage.getList());
		request.setAttribute("bookClass",bookClass);
		request.setAttribute("page", bookPage);

		return "staff/staff_book_searchResult";
	}

	/* 借阅图书操作*/
	@RequestMapping(value = "borrowBook",method = RequestMethod.POST)
	public String borrowBook(@RequestParam("bookId") String bookId,
						   HttpServletRequest request,RedirectAttributes attr) throws ParseException {
		Staff s = (Staff)request.getSession().getAttribute("staff");
		Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
		int currentBorrowNumber = this.borrowServiceImpl.getCurrentBooksByStaff(s).size();	//当前借阅数量
		BookClass bc = book.getBookClass();
		Map paramsMap = new HashMap();

		if(book.getState() != BookState.ENABLE_BORROW.getState()){		//书籍已经借出或丢失
			attr.addFlashAttribute("error","书籍没有在库");
			return "redirect:/staff/bookSearchPage";
		}else if(s.isState()){	//该员工被禁止操作
			attr.addFlashAttribute("error","你没有权限借书，请联系管理员");
			return "redirect:/staff/bookSearchPage";
		}else if(s.getMaxBorrowNumber() <= currentBorrowNumber){	//超过最大借阅数量
			attr.addFlashAttribute("error","你的借阅数量已达到最大值,无法借阅");
			return "redirect:/staff/bookSearchPage";
		}

		/*更新图书状态*/
		book.setState(BookState.BORROWED.getState());	//修改图书状态 已借出
		book.setBorrowTimes(book.getBorrowTimes() + 1);	//借阅次数增1

        Set<Staff> staffSet= book.getStaffs();
		Iterator<Staff> iterator = staffSet.iterator();
		Staff staff;
		boolean flag = false;
		while(iterator.hasNext()){
			staff = iterator.next();
			if(s.getStaffId() == staff.getStaffId()){	//已经存在
				flag = true;
				break;
			}
		}
		if(!flag){
			staffSet.add(s);
			book.setStaffs(staffSet);
		}
		this.bookServiceImpl.editBook(book);

		s = this.staffServiceImpl.getStaff(s.getStaffId());
		s.setBorrowedNumber(s.getBorrowedNumber() + 1);	//已借数量增一
		this.staffServiceImpl.updateStaff(s);

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Borrow borrow = new Borrow();
		Date date = new Date();

		borrow.setStaff(s);
		borrow.setBook(book);
		borrow.setState(BorrowState.GETTING_BOOK.getState());
		borrow.setStartDate(formatter.format(date));
		borrow.setEndDate(formatter.format(date.getTime() +  24*60*60*1000*20));
		borrow.setBorrowDays(borrow.getBorrowDays());
		borrow.setEndDays(borrow.getEndDays());

		this.borrowServiceImpl.addBorrow(borrow);

        paramsMap.put("staff",s);
        paramsMap.put("bookClass",bc);
        Statistic statistic = this.statisticServiceImpl.getStatisticByParams(paramsMap);

        paramsMap.clear();
        paramsMap.put("staff",s);

        int sumBorrowTime = 1;
		int sumSearchTime = 1;
		Long temp;
        Double percentage = 0.0;

		if( (temp = this.borrowServiceImpl.getBorrowsCountByParams(paramsMap)) != null){
			sumBorrowTime = temp.intValue();
		}
		if((temp = this.searchServiceImpl.getStaffSearchsCountByParams(paramsMap)) != null){
			sumSearchTime = temp.intValue();
		}

		formatter = new SimpleDateFormat("yyyy-MM");
        if(statistic != null){
            statistic.setSearchTime(statistic.getSearchTime() + 1);	//增加借阅次数
            percentage = ((statistic.getBorrowTime() * 100 / sumBorrowTime) * 0.8 + (statistic.getSearchTime() * 100 / sumSearchTime) * 0.2);
            statistic.setPercentage(String.valueOf(percentage.intValue()));
            this.statisticServiceImpl.updateStatistic(statistic);
        } else{		//statistic 为空
            statistic = new Statistic();
            statistic.setBookClass(bc);
            statistic.setBorrowTime(0);
            statistic.setSearchTime(1);
            percentage = ((statistic.getBorrowTime() * 100 / sumBorrowTime) * 0.8 + (statistic.getSearchTime() * 100 / sumSearchTime) * 0.2);
            statistic.setPercentage(String.valueOf(percentage.intValue()));
            statistic.setStaff(s);
			statistic.setDate(formatter.format(date));

            this.statisticServiceImpl.addStatistic(statistic);
        }

        paramsMap.put("date",formatter.format(date));
        Count count = this.countServiceImpl.getCountByParams(paramsMap);
        if(count != null){
            count.setBorrowCount(count.getBorrowCount() + 1);
            this.countServiceImpl.updateCount(count);
        }else{
            count = new Count();
            count.setBorrowCount(1);
            count.setStaffCount(0);
            count.setEvaluateCount(0);
            count.setBookCount(0);
            count.setSearchCount(0);
            count.setPaymentCount(this.paymentServiceImpl.getPaymentCostByParams(paramsMap).intValue());
            count.setStaff(s);
            count.setDate(formatter.format(date));

            this.countServiceImpl.addCount(count);
        }
		request.setAttribute("borrowType",0);
		request.setAttribute("book",book);
		request.setAttribute("success","借书成功,书籍可借20天,到时请及时归还.现可去图书处取书");
		return "staff/staff_success";
	}

	/*跳转到图书信息*/
	@RequestMapping("bookInfoPage")
	public String bookInfoPage(@RequestParam("bookId") String bookId,
									HttpServletRequest request,RedirectAttributes attr){
		Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
		Staff staff = (Staff) request.getSession().getAttribute("staff");
		List<Evaluate> evaluates = this.evaluateServiceImpl.getTopThreeEvaluateOrderByPraiseDesc(book);
		List<Praise> praises = this.praiseServiceImpl.getPraise(staff);

		book.setBrowseTimes(book.getBrowseTimes() + 1);			//浏览次数增1
		this.bookServiceImpl.editBook(book);

		if(book == null){
			attr.addFlashAttribute("error","该书不存在");
			return "redirect:/staff/bookSearchPage";
		}else{
			request.setAttribute("book",book);
			request.setAttribute("evaluates",evaluates);
			request.setAttribute("praises",praises);
			request.setAttribute("collection",this.collectionServiceImpl.getCollectionByStaff(staff));

			return "staff/staff_book_info";
		}

	}

	/*
	* 获得更多评论操作
	* return Json
	* */
	@ResponseBody
	@RequestMapping(value = "getEvaluate", method = RequestMethod.POST)
	public ReturnJson getEvaluate(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		int bookId;
		int pageNum = 2;
		int pageSize = 5;

		Page<Evaluate> evaluatePage;
		Map<String,Object> data = new HashMap();

		if(params.get("bookId") != null){
			bookId = Integer.parseInt(params.get("bookId"));
			pageNum = Integer.parseInt(params.get("pageNum"));

			Book book = this.bookServiceImpl.getBook(bookId);
			evaluatePage = this.evaluateServiceImpl.getPageOrderByPraiseDesc(pageNum,pageSize,book);
			EvaluateListReturner evaluateListReturner = new EvaluateListReturner(evaluatePage.getList());

			data.put("evaluates",evaluateListReturner.getEvaluates());
			data.put("pageNum",evaluatePage.getCurrentPageNum());

		}else{
			return new ReturnJson(false,"失败了，评论ID不存在");
		}

		return new ReturnJson(true,"",data);
	}

	/*跳转到我的当前借阅*/
	@RequestMapping("myBooksPage")
	public String myBookPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
							 @RequestParam(name="pageSize", defaultValue="10")int pageSize,
							HttpServletRequest request, RedirectAttributes attr){
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		Page<Borrow> borrowPage = this.borrowServiceImpl.getCurrentBorrowsByStaff(pageNum,pageSize,staff);

		if(attr.getFlashAttributes().get("error") != null){
			request.setAttribute("error",attr.getFlashAttributes().get("error"));
		}else if(attr.getFlashAttributes().get("success") != null){
			request.setAttribute("success",attr.getFlashAttributes().get("success"));
		}

		request.setAttribute("borrows",borrowPage.getList());
		request.setAttribute("page",borrowPage);
		return "staff/staff_book_my";
	}

	/* 归还图书操作*/
	@RequestMapping(value = "returnBook",method = RequestMethod.POST)
	public String returnBook(@RequestParam("borrowId") String borrowId,
							 HttpServletRequest request, RedirectAttributes attr) throws ParseException {
		Staff s= (Staff)request.getSession().getAttribute("staff");
		Borrow borrow = this.borrowServiceImpl.getBorrow(Integer.parseInt(borrowId));

		if(borrow.getBook().getState() != BookState.BORROWED.getState()){
			attr.addFlashAttribute("error","书籍并不在借阅中,无法归还");
			return "redirect:/staff/myBooksPage";
		}else if(s.isState()){	//该员工被禁止操作
			attr.addFlashAttribute("error","你没有权限还书，请联系管理员");
			return "redirect:/staff/myBooksPage";
		}

		borrow.setState(BorrowState.RETURNING_BOOK.getState());	//设置借阅状态为归还中
		this.borrowServiceImpl.updateBorrow(borrow);

		attr.addFlashAttribute("success","归还申请成功,您可评价图书");

		/*判断员工等级与升级*/
		this.staffServiceImpl.staffGrade(s);

		return "redirect:/staff/myBooksPage";
	}


    /*跳转到图书评价页面*/
    @RequestMapping(value = "bookEvaluePage",method = RequestMethod.POST)
    public String bookEvaluePage(@RequestParam("borrowId") String borrowId,
                                 HttpServletRequest request,RedirectAttributes attr){
		Borrow borrow = this.borrowServiceImpl.getBorrow(Integer.parseInt(borrowId));
        Book book = borrow.getBook();
        if(book == null){
			attr.addFlashAttribute("error","该书不存在");
            return "redirect:/staff/bookSearchPage";
        }else{
            request.setAttribute("book",book);
			request.setAttribute("borrow",borrow);
            return "staff/staff_book_evaluate";
        }

    }

    /*图书评价操作*/
    @RequestMapping(value = "bookEvalue",method = RequestMethod.POST)
    public String bookEvalue(@RequestParam("borrowId") String borrowId,
							  @RequestParam("grade") String grade,
                              @RequestParam("description") String description,
                                 HttpServletRequest request,RedirectAttributes attr){
		Borrow borrow = this.borrowServiceImpl.getBorrow(Integer.parseInt(borrowId));
        Book book = borrow.getBook();
        Staff staff = (Staff) request.getSession().getAttribute("staff");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Set<Power> powers = staff.getRole().getPowers();

		Iterator<Power> it = powers.iterator();
        boolean flag = false;
        while (it.hasNext()){
            if(it.next().getType() == 6){
                flag = true;
                break;
            }
        }
        if(!flag){
			attr.addFlashAttribute("error","你没有权限评论,请联系管理员");
            return "redirect:/staff/bookSearchPage";
        }

        if(book == null){
			attr.addFlashAttribute("error","该书不存在");
            return "redirect:/staff/bookSearchPage";
        }else if(staff.isState()){
			attr.addFlashAttribute("error","你没有权限评论,请联系管理员");
            return "redirect:/staff/bookSearchPage";
        }else{
            Evaluate evaluate = new Evaluate();
            evaluate.setStaff(staff);
            evaluate.setBook(book);
            evaluate.setDescription(Escape.encode(description));
			evaluate.setGrade(Float.parseFloat(grade));
			evaluate.setDate(formatter.format(new Date()));
			evaluate.setBorrow(borrow);
			evaluate.setPraise(0);
			evaluate.setForbidden(0);
			this.evaluateServiceImpl.addEvaluate(evaluate);

			if(!grade.equals("")){
				book.setGrade(this.evaluateServiceImpl.getBookAveGrade(book));

                Set staffSet = book.getStaffs();
				Iterator<Staff> iterator = staffSet.iterator();
				Staff s;
				while(iterator.hasNext()){
					s = iterator.next();
					if(s.getStaffId() == staff.getStaffId()){	//已经存在
						flag = true;
						break;
					}
				}
				if(!flag){
					staffSet.add(staff);
					book.setStaffs(staffSet);
				}
				this.bookServiceImpl.editBook(book);
            }

          	attr.addFlashAttribute("success","评价成功,感谢借阅书籍!");
            return "redirect:/staff/myBooksPage";
        }

    }

	/*
	* 点赞评论操作
	* return Json
	* */
	@ResponseBody
	@RequestMapping(value = "praiseEvaluate", method = RequestMethod.POST)
	public ReturnJson praiseEvaluate(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		int evaluateId;
		Staff staff = (Staff)session.getAttribute("staff");
		Praise praise;

		if(params.get("evaluateId") != null){
			evaluateId = Integer.parseInt(params.get("evaluateId"));
			Evaluate evaluate = this.evaluateServiceImpl.getEvaluateById(evaluateId);

			if(params.get("type").equals("0")){
				evaluate.setPraise(evaluate.getPraise() + 1);

                praise = new Praise();
                praise.setEvaluate(evaluate);
                praise.setStaff(staff);
                this.praiseServiceImpl.addPraise(praise);

            }else{
                praise = this.praiseServiceImpl.getPraise(staff,evaluate);
				evaluate.setPraise(evaluate.getPraise() - 1);
                this.praiseServiceImpl.deletePraise(praise.getPraiseId());
            }

			this.evaluateServiceImpl.updateEvaluate(evaluate);

			/*记录员工之间的联系*/
			Staff s1 = staff;		//员工甲
			Staff s2 = evaluate.getStaff();		//员工乙
			StaffRelation staffRelation = this.staffRelationService.getStaffRelation(s1,s2);

			if(staffRelation != null){
				staffRelation.setCount(staffRelation.getCount() + 1);
				this.staffRelationService.updateRelation(staffRelation);
			}else{
				staffRelation = new StaffRelation();
				staffRelation.setStaffOne(s1);
				staffRelation.setStaffTwo(s2);
				staffRelation.setCount(1);
				this.staffRelationService.addRelation(staffRelation);
			}

			//反向记录员工之间的联系
			staffRelation = this.staffRelationService.getStaffRelation(s2,s1);
			if(staffRelation != null){
				staffRelation.setCount(staffRelation.getCount() + 1);
				this.staffRelationService.updateRelation(staffRelation);
			}else{
				staffRelation = new StaffRelation();
				staffRelation.setStaffOne(s2);
				staffRelation.setStaffTwo(s1);
				staffRelation.setCount(1);
				this.staffRelationService.addRelation(staffRelation);
			}

		}else {
			return new ReturnJson(false,"失败了，评论ID不存在");
		}

		return new ReturnJson();
	}

	/*
	* 举报评论操作
	* return Json
	* */
	@ResponseBody
	@RequestMapping(value = "forbiddenEvaluate", method = RequestMethod.POST)
	public ReturnJson forbiddenEvaluate(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		int evaluateId;

		if(params.get("evaluateId") != null){
			evaluateId = Integer.parseInt(params.get("evaluateId"));
			Evaluate evaluate = this.evaluateServiceImpl.getEvaluateById(evaluateId);
			evaluate.setForbidden(evaluate.getForbidden() + 1);

			this.evaluateServiceImpl.updateEvaluate(evaluate);
		}else {
			return new ReturnJson(false,"失败了,评论ID不存在");
		}

		return new ReturnJson();
	}

	/* 挂失图书操作*/
	@RequestMapping(value = "lostBook",method = RequestMethod.POST)
	public String lostBook(@RequestParam("borrowId") String borrowId,
							 HttpServletRequest request,RedirectAttributes attr) throws ParseException {
		Staff s= (Staff)request.getSession().getAttribute("staff");
		Borrow borrow = this.borrowServiceImpl.getBorrow(Integer.parseInt(borrowId));
		Book book = borrow.getBook();

		if(borrow.getBook().getState() != BookState.BORROWED.getState()){
			attr.addFlashAttribute("error","书籍并不在借阅中,无法挂失");
			return "redirect:/staff/myBooksPage";
		}else if(s.isState()){	//该员工被禁止操作
			attr.addFlashAttribute("error","你没有权限挂失，请联系管理员");
			return "redirect:/staff/myBooksPage";
		}

		borrow.setState(BorrowState.LOST_BOOK.getState());	//设置借阅状态为挂失中
		this.borrowServiceImpl.updateBorrow(borrow);
		book.setState(BookState.LOST.getState());	//设置图书状态为丢失
		this.bookServiceImpl.editBook(book);

		attr.addFlashAttribute("success","挂失申请成功,请及时到图书处联系管理员进行挂失处理");
		return "redirect:/staff/myBooksPage";
	}

	/* 续借图书操作*/
	@RequestMapping(value = "continueBorrow",method = RequestMethod.POST)
	public String continueBorrow(@RequestParam("borrowId") String borrowId,
						   HttpServletRequest request,RedirectAttributes attr) throws ParseException {
		Staff s= (Staff)request.getSession().getAttribute("staff");
		Borrow borrow = this.borrowServiceImpl.getBorrow(Integer.parseInt(borrowId));

		if(borrow.getBook().getState() != BookState.BORROWED.getState()){		//书籍并不在借阅中,无法续借
			attr.addFlashAttribute("error","书籍并不在借阅中,无法续借");
			return "redirect:/staff/myBooksPage";
		}else if(s.isState()){	//该员工被禁止操作  没有权限借书
			attr.addFlashAttribute("error","你没有权限续借，请联系管理员");
			return "redirect:/staff/myBooksPage";
		}else if(borrow.getEndDays() <= 5){	//还有小于等于5天需要还书，无法续借
			attr.addFlashAttribute("error","小于5天还书,无法续借");
			return "redirect:/staff/myBooksPage";
		}else if(borrow.getAllDays() > 40){	//总共时长超过40天了
			attr.addFlashAttribute("error","总共时长超过40天,无法续借");
			return "redirect:/staff/myBooksPage";
		}else if(borrow.getEndDays() >= 10){	//还有大于等于10天需要还书，无法续借
            attr.addFlashAttribute("error","续借日期未到,无法续借");
			return "redirect:/staff/myBooksPage";
		}
		this.borrowServiceImpl.continueBorrow(borrow);	//续借

		attr.addFlashAttribute("success","续借申请成功,请及时还书");
		return "redirect:/staff/myBooksPage";
	}

	/*跳转到我的历史借阅*/
	@RequestMapping("myHistoryPage")
	public String myHistoryPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
								 @RequestParam(name="pageSize", defaultValue="10") String pageSize,
							 	 HttpServletRequest request){
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		Page<Borrow> borrowPage;

		if(pageSize.equals("all")){
			List<Borrow> borrows = this.borrowServiceImpl.getHistoryBorrowsByStaff(staff);
			borrowPage= new Page<>();
			borrowPage.setPageSize(borrows.size());
			borrowPage.setTotalCount(borrows.size());
			borrowPage.setList(borrows);
			borrowPage.setCurrentPageNum(1);
			borrowPage.setTotalPageNum(1);
		}else{
			borrowPage = this.borrowServiceImpl.getHistoryBorrowsByStaff(pageNum,Integer.parseInt(pageSize),staff);
		}

		request.setAttribute("borrows",borrowPage.getList());
		request.setAttribute("page", borrowPage);

		return "staff/staff_book_history";
	}

	/*搜索关键词热度排行榜单*/
	@RequestMapping("hotKeyPage")
	public String hotKeyPage(HttpServletRequest request){
		List<StaffSearch> searchs = this.searchServiceImpl.getHotSearch(50);
		List<BookClass> bc = this.bookClassServiceImpl.getAllBookClasses();
		int sumCount = 0;

		for(int i = 0;i < searchs.size();++i)
			sumCount += searchs.get(i).getSearchCount();

		request.setAttribute("searchs",searchs);
		request.setAttribute("sumCount",sumCount);
		request.setAttribute("bookClasses",bc);


		return "staff/staff_search_rank";
	}

	/*搜索关键词热度排行榜单*/
	@RequestMapping(value = "hotBookPage",method = RequestMethod.GET)
	public String hotBookPage(@RequestParam(name="bookClassId") String bookClassId,
							  HttpServletRequest request){
		List<StaffSearch> searchs = this.searchServiceImpl.getHotSearch(50);
		List<BookClass> bc = this.bookClassServiceImpl.getAllBookClasses();
        List<Book> hotBooks = new ArrayList<>();
        BookClass bookClass = null;
		Map paramsMap = new HashMap();
		int sumCount = 0;

        if(!bookClassId.equals("all")){
            bookClass = this.bookClassServiceImpl.getBookClass(Integer.parseInt(bookClassId));
            paramsMap.put("bookClass",bookClass);
            hotBooks = this.bookServiceImpl.getBooksByHot(paramsMap,50);
        }else{
            hotBooks = this.bookServiceImpl.getBooksByHot(new HashMap(),50);
        }

		for(int i = 0;i < hotBooks.size();++i)
			sumCount += hotBooks.get(i).getBorrowTimes();

		request.setAttribute("searchs",searchs);
		request.setAttribute("bookClasses",bc);
        request.setAttribute("hotBooks",hotBooks);
		request.setAttribute("sumCount",sumCount);

		return "staff/staff_hotBook_page";
	}

	/*
	* 收藏图书操作
	* return Json
	* */
	@ResponseBody
	@RequestMapping(value = "likeBook", method = RequestMethod.POST)
	public ReturnJson likeBook(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		int bookId;
		Staff staff = (Staff)session.getAttribute("staff");
		Collection collection = this.collectionServiceImpl.getCollectionByStaff(staff);

		/*收藏图书*/
		if(params.get("bookId") != null){
			bookId = Integer.parseInt(params.get("bookId"));
			Book book = this.bookServiceImpl.getBook(bookId);
			Set<Book> books = collection.getBooks();

			books.add(book);
			collection.setBooks(books);

			this.collectionServiceImpl.updateCollection(collection);

			//记录图书与员工的联系
			Set staffSet = book.getStaffs();
			Iterator<Staff> iterator = staffSet.iterator();
			Staff s;
			boolean flag = false;

			while(iterator.hasNext()){
				s = iterator.next();
				if(s.getStaffId() == staff.getStaffId()){	//已经存在
						flag = true;
						break;
				}
			}
			if(!flag){
				staffSet.add(staff);
				book.setStaffs(staffSet);
			}
			this.bookServiceImpl.editBook(book);
		}else {
			return new ReturnJson(false,"失败了,图书不存在");
		}

		return new ReturnJson();
	}


	/*
	* 取消收藏图书操作
	* return Json
	* */
	@ResponseBody
	@RequestMapping(value = "removeLikeBook", method = RequestMethod.POST)
	public ReturnJson removeLikeBook(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		int bookId;
		Staff staff = (Staff)session.getAttribute("staff");
		Collection collection = this.collectionServiceImpl.getCollectionByStaff(staff);

		if(params.get("bookId") != null){
			bookId = Integer.parseInt(params.get("bookId"));
			Book book = this.bookServiceImpl.getBook(bookId);
			Set<Book> books = collection.getBooks();

			books.remove(book);
			collection.setBooks(books);

			this.collectionServiceImpl.updateCollection(collection);
		}else {
			return new ReturnJson(false,"失败了，bookId不存在");
		}

		return new ReturnJson();
	}

	/*跳转到我的收藏夹*/
	@RequestMapping("myCollectionPage")
	public String myCollectionPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
								@RequestParam(name="pageSize", defaultValue="10") String pageSize,
								HttpServletRequest request){
		Staff staff = (Staff)request.getSession().getAttribute("staff");

		request.setAttribute("collection",this.collectionServiceImpl.getCollectionByStaff(staff));

		return "staff/staff_book_collection";
	}

	/************************ 推荐读友 ***************************/
	/*************************************************************/
	/*跳转到推荐读友*/
	@RequestMapping("recommendationStaffPage")
	public String recommendationStaffPage(HttpServletRequest request){
		Staff staff = (Staff)request.getSession().getAttribute("staff");
		List<Book> books = this.bookServiceImpl.getAllBooks();	//得到全部图书
		Set<Staff> staffs= this.staffRelationService.getRecommendationStaffByStaff(staff);	//找到推荐的读友
		Circles circles = this.circlesServiceImpl.getCirclesByStaff(staff);	//获得朋友圈
        staffs.removeAll(circles.getFollowStaffs());    //去掉我关注的

        Iterator<Staff> staffIterator = staffs.iterator();
        Staff recommendStaff = null;

        //取前5个推荐
        while(staffIterator.hasNext() && staffs.size() > 5){	//推荐列表长度大于5需要筛选
            recommendStaff = staffIterator.next();
            staffs.remove(recommendStaff);
        }

		request.setAttribute("collection",this.collectionServiceImpl.getCollectionByStaff(staff));
		request.setAttribute("staffs",staffs);
		request.setAttribute("circles",circles);

		return "staff/staff_recommendation_staff";
	}

	/*跳转到读友历史借阅*/
	@RequestMapping(value = "friendHistory",method = RequestMethod.POST)
	public String friendHistory(@RequestParam(name = "staffId") String staffId,
								@RequestParam(name="pageNum", defaultValue="1") int pageNum,
								@RequestParam(name="pageSize", defaultValue="10") String pageSize,
								HttpServletRequest request){
		Staff staff = (Staff)this.staffServiceImpl.getStaff(Integer.parseInt(staffId));
		Page<Book> bookPage;

		if(pageSize.equals("all")){
			List<Book> books = this.bookServiceImpl.getBooksByStaff(staff);
			bookPage= new Page<>();
			bookPage.setPageSize(books.size());
			bookPage.setTotalCount(books.size());
			bookPage.setList(books);
			bookPage.setCurrentPageNum(1);
			bookPage.setTotalPageNum(1);
		}else{
			bookPage = this.bookServiceImpl.getBooksByStaff(pageNum,Integer.parseInt(pageSize),staff);
		}

		request.setAttribute("books",bookPage.getList());
		request.setAttribute("page", bookPage);
		request.setAttribute("friend",staff);

		return "staff/staff_friend_history";
	}

    /*
    * 关注读友操作
    * return Json
    * */
    @ResponseBody
    @RequestMapping(value = "followFriend", method = RequestMethod.POST)
    public ReturnJson followFriend(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
        int staffId;
        Staff staff = (Staff)session.getAttribute("staff");
        Circles circles = this.circlesServiceImpl.getCirclesByStaff(staff);

		/*关注好友*/
        if(params.get("staffId") != null){
            staffId = Integer.parseInt(params.get("staffId"));
            Staff s = this.staffServiceImpl.getStaff(staffId);  //被关注的读友

            Set<Staff> staffs = circles.getFollowStaffs();
			if(staffs != null){
				staffs.add(s);
			}else{
				staffs = new HashSet<Staff>();
				staffs.add(s);
			}
			circles.setFollowStaffs(staffs);
            this.circlesServiceImpl.updateCircles(circles);

            circles = this.circlesServiceImpl.getCirclesByStaff(s);     //被关注读友的粉丝圈
            Set<Staff> followers = circles.getFollowers();
			if(followers != null){
				followers.add(staff);
			}else{
				followers = new HashSet<Staff>();
				followers.add(staff);
			}
			circles.setFollowers(followers);
            this.circlesServiceImpl.updateCircles(circles);
        }else {
            return new ReturnJson(false,"失败了，staffId不存在");
        }

        return new ReturnJson();
    }

    /*
 	 * 取消关注读友操作
  	* return Json
  	* */
    @ResponseBody
    @RequestMapping(value = "removeFollowFriend", method = RequestMethod.POST)
    public ReturnJson removeFollowFriend(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
        int staffId;
        Staff staff = (Staff)session.getAttribute("staff");
        Circles circles = this.circlesServiceImpl.getCirclesByStaff(staff);

		/*取关好友*/
        if(params.get("staffId") != null){
            staffId = Integer.parseInt(params.get("staffId"));
            Staff s = this.staffServiceImpl.getStaff(staffId);  //被关注的读友

            Set<Staff> staffs = circles.getFollowStaffs();
            staffs.remove(s);
            circles.setFollowStaffs(staffs);
            this.circlesServiceImpl.updateCircles(circles);

            circles = this.circlesServiceImpl.getCirclesByStaff(s);     //被关注读友的粉丝圈
            Set<Staff> followers = circles.getFollowers();
            followers.remove(this.staffServiceImpl.getStaff(staff.getStaffId()));
            circles.setFollowers(followers);

            this.circlesServiceImpl.updateCircles(circles);
        }else {
            return new ReturnJson(false,"失败了，staffId不存在");
        }

        return new ReturnJson();
    }


    /*跳转到我的关注*/
    @RequestMapping("myFollowFriends")
    public String myFollowFriends(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                   @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                   HttpServletRequest request){
        Staff staff = (Staff)request.getSession().getAttribute("staff");
		Circles circles = this.circlesServiceImpl.getCirclesByStaff(staff);

        request.setAttribute("staffs",this.circlesServiceImpl.getCirclesByStaff(staff).getFollowStaffs());
		request.setAttribute("state",0);
		request.setAttribute("circles",circles);
		request.setAttribute("title","我的关注");

        return "staff/staff_my_friends";
    }

    /*跳转到关注我的粉丝*/
    @RequestMapping("myFollowers")
    public String myFollowers(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                  @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                  HttpServletRequest request){
        Staff staff = (Staff)request.getSession().getAttribute("staff");
		Circles circles = this.circlesServiceImpl.getCirclesByStaff(staff);	//获得朋友圈

        request.setAttribute("staffs",this.circlesServiceImpl.getCirclesByStaff(staff).getFollowers());
		request.setAttribute("state",1);
		request.setAttribute("circles",circles);
		request.setAttribute("title","我的粉丝");

        return "staff/staff_my_friends";
    }

	/*跳转到读友数据*/
	@RequestMapping(value = "friendData",method = RequestMethod.POST)
	public String friendData(@RequestParam(name = "staffId") String staffId,
								  HttpServletRequest request){
		Staff staff = this.staffServiceImpl.getStaff(Integer.parseInt(staffId));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		Date date = new Date();
		Map paramsMap = new HashMap();

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date); // 设置为当前时间
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月

		paramsMap.put("staff",staff);    //查询指定员工统计数据
		Count count = this.countServiceImpl.getSumCountByParams(paramsMap);
		List<Statistic> statistics = this.statisticServiceImpl.getStatisticsByParams(paramsMap);
		List<Count> counts = this.countServiceImpl.getCountsByParams(paramsMap);

		for(int i = counts.size() - 1;i > 5;--i){
			counts.remove(i);
		}
		for(int i = statistics.size() - 1;i > 5;--i){
			statistics.remove(i);
		}

		int paymentCount = this.paymentServiceImpl.getPaymentCountByParams(paramsMap).intValue();

		request.setAttribute("count",count);
		request.setAttribute("counts",counts);
		request.setAttribute("paymentCounts",paymentCount);
		request.setAttribute("statistics",statistics);
		request.setAttribute("staff",staff);

		return "staff/staff_staff_data";
	}

	/*******************************图书推荐***********************************/
	/*跳转到推荐图书*/
	@RequestMapping("recommendationBooksPage")
	public String recommendationBooksPage(HttpServletRequest request){
		Staff staff = (Staff)request.getSession().getAttribute("staff");
        Circles circles = this.circlesServiceImpl.getCirclesByStaff(staff); //朋友圈
        Set<Staff> myFollows = circles.getFollowStaffs();          //关注的读友
        List<Staff> staffs = new ArrayList<Staff>();
		Set<Staff> staffSet = new HashSet<Staff>();
		Set<Book> bookSet;

        staffs.addAll(myFollows);	//	添加我关注的
		staffs.addAll(this.staffRelationService.getRecommendationStaffByStaff(staff));	//将推荐的好友也加进去

		Recommendation recommendation = this.recommendationServiceImpl.getRecommendationByStaff(staff);		//获得推荐条目
		RecommendBook recommendBook = null;

		//更新推荐图书
		this.recommendationServiceImpl.updateRecommendationBooksByStaffs(recommendation,staffs);

		List<RecommendBook> recommendBooks = new ArrayList<RecommendBook>();
		recommendBooks.addAll(recommendation.getRecommendBooks());  //图书推荐

		//取前5个推荐
		for(int i = recommendBooks.size() - 1;i >= 5;--i){ //推荐列表长度大于5需要筛选
			recommendBooks.remove(i);
		}

		request.setAttribute("recommendBooks",recommendBooks);
		return "staff/staff_recommendation_book";
	}


	/*
	* 更新推荐
	* 基于用户协同过滤
	* return Json
	*
	* */
	@ResponseBody
	@RequestMapping(value = "updateUserRecommendation", method = RequestMethod.POST)
	public ReturnJson updateUserRecommendation(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		Staff s = (Staff) session.getAttribute("staff");
		Book book = null;

		if(params.get("bookId") != null){
			book = this.bookServiceImpl.getBook(Integer.parseInt(params.get("bookId")));
		}
		s = this.staffServiceImpl.getStaff(s.getStaffId());

		/*更新推荐读友*/
		List<Book> bookList = new ArrayList<Book>();
		bookList.add(book);
		this.staffRelationService.updateAllRelationByBooks(s,bookList);	//更新员工之间的关系

		return new ReturnJson(true,null);
	}

	/*
	* 更新推荐
	* 基于物品协同过滤
	* return Json
	*
	* */
	@ResponseBody
	@RequestMapping(value = "updateBookRecommendation", method = RequestMethod.POST)
	public ReturnJson updateBookRecommendation(@RequestBody Map<String, String> params, HttpSession session) throws Exception {
		Staff s = (Staff) session.getAttribute("staff");
		s = this.staffServiceImpl.getStaff(s.getStaffId());

		/* 更新图书关系 */
		//基于员工的行为更新图书之间的关系
		List<Staff> staffList = new ArrayList<Staff>();
		staffList.add(s);
		this.bookRelationServiceImpl.updateAllRelationByStaffs(s,staffList);   //更新员工staff相关的图书关系记录

		return new ReturnJson(true,null);
	}
}
